package paidaxing.blog.comment.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import paidaxing.blog.comment.dto.LikeDTO;
import paidaxing.blog.comment.dto.request.LikeRequestDTO;
import paidaxing.blog.comment.entity.Comments;
import paidaxing.blog.comment.entity.Likes;
import paidaxing.blog.comment.mapper.CommentMapper;
import paidaxing.blog.comment.mapper.LikeMapper;
import paidaxing.blog.comment.service.LikeService;
import paidaxing.blog.post.entity.Posts;
import paidaxing.blog.post.mapper.PostsDao;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LikeServiceImpl implements LikeService {
    @Resource
    private LikeMapper likeMapper;
    
    @Resource
    private PostsDao postsDao;
    
    @Resource
    private CommentMapper commentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleLike(LikeRequestDTO likeRequestDTO) {
        Long userId = StpUtil.getLoginIdAsLong(); // 使用当前登录用户ID
        String targetType = likeRequestDTO.getTargetType();
        Long targetId = likeRequestDTO.getTargetId();
        
        // 检查是否已经点赞
        Likes existingLike = likeMapper.selectByCondition(userId, targetType, targetId);
        
        if (existingLike != null) {
            // 已点赞，执行取消点赞操作
            int result = likeMapper.deleteByCondition(userId, targetType, targetId);
            if (result > 0) {
                // 同步更新目标实体的点赞计数
                updateTargetLikeCount(targetType, targetId, false);
                return true;
            }
            return false;
        } else {
            // 未点赞，执行点赞操作
            Likes likes = new Likes();
            likes.setUserId(userId);
            likes.setTargetType(targetType);
            likes.setTargetId(targetId);
            likes.setCreatedAt(new Date());
            
            int result = likeMapper.insert(likes);
            if (result > 0) {
                // 同步更新目标实体的点赞计数
                updateTargetLikeCount(targetType, targetId, true);
                return true;
            }
            return false;
        }
    }
    
    /**
     * 更新目标实体的点赞计数
     * @param targetType 目标类型
     * @param targetId 目标ID
     * @param increment 是否增加计数
     */
    private void updateTargetLikeCount(String targetType, Long targetId, boolean increment) {
        if ("POST".equals(targetType)) {
            // 更新文章的点赞计数
            Posts post = postsDao.queryById(targetId);
            if (post != null) {
                Integer likeCount = post.getLikeCount();
                if (likeCount == null) {
                    likeCount = 0;
                }
                post.setLikeCount(increment ? likeCount + 1 : likeCount - 1);
                postsDao.update(post);
            }
        } else if ("COMMENT".equals(targetType)) {
            // 更新评论的点赞计数
            Comments comment = commentMapper.queryById(targetId);
            if (comment != null) {
                Integer likeCount = comment.getLikeCount();
                if (likeCount == null) {
                    likeCount = 0;
                }
                comment.setLikeCount(increment ? likeCount + 1 : likeCount - 1);
                commentMapper.update(comment);
            }
        }
    }

    @Override
    public boolean getLikeStatus(Long userId, String targetType, Long targetId) {
        // 直接使用传入的userId进行检查，不再从StpUtil获取
        Likes likes = likeMapper.selectByCondition(userId, targetType, targetId);
        return likes != null;
    }

    @Override
    public List<LikeDTO> getLikesByPostId(Long postId) {
        List<Likes> likesList = likeMapper.selectByTarget("POST", postId);
        
        return likesList.stream().map(like -> {
            LikeDTO dto = new LikeDTO();
            BeanUtils.copyProperties(like, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<LikeDTO> getLikesByCommentId(Long commentId) {
        List<Likes> likesList = likeMapper.selectByTarget("COMMENT", commentId);
        
        return likesList.stream().map(like -> {
            LikeDTO dto = new LikeDTO();
            BeanUtils.copyProperties(like, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public Integer getLikeCount(String targetType, Long targetId) {
        return likeMapper.countByTarget(targetType, targetId);
    }
}